<template>
  <div class="reservation-management">
    <el-card shadow="hover" class="!border-0">
      <template #header>
        <div class="flex items-center justify-between">
          <div>
            <h2 class="text-xl font-semibold text-gray-800">订单管理</h2>
            <p class="text-gray-500 text-sm">查看和管理所有会议室预订订单</p>
          </div>
          <div class="flex gap-2 items-center">
            <el-input
              v-model="roomNameSearch"
              placeholder="搜索会议室..."
              clearable
              style="width: 180px"
              @clear="fetchReservations"
              @keyup.enter="fetchReservations"
            />
            <el-input
              v-model="customerNameSearch"
              placeholder="搜索客户..."
              clearable
              style="width: 180px"
              @clear="fetchReservations"
              @keyup.enter="fetchReservations"
            />
            <el-select
              v-model="statusFilter"
              placeholder="筛选状态"
              clearable
              style="width: 150px"
              @change="fetchReservations"
            >
              <el-option label="待支付" value="PENDING_PAYMENT" />
              <el-option label="已确认" value="CONFIRMED" />
              <el-option label="支付超时" value="PAYMENT_EXPIRED" />
              <el-option label="取消申请中" value="CANCELLATION_REQUESTED" />
              <el-option label="已取消" value="CANCELLED" />
              <el-option label="已预约" value="SCHEDULED" />
              <el-option label="使用中" value="IN_USE" />
              <el-option label="已完成" value="COMPLETED" />
            </el-select>
            <div class="flex gap-2">
              <el-button @click="resetSearch" plain>重置</el-button>
              <el-button
                @click="fetchReservations"
                :loading="loading"
                type="primary"
                class="refresh-button"
              >
                <RefreshCw class="h-4 w-4" />
              </el-button>
            </div>
          </div>
        </div>
      </template>

      <el-alert
        v-if="isSearching"
        type="info"
        :closable="false"
        title="正在搜索中..."
        class="mb-4"
      />

      <el-table
        :data="paginatedReservations"
        v-loading="loading"
        style="width: 100%"
        :default-sort="{ prop: 'startTime', order: 'descending' }"
      >
        <el-table-column prop="bookingId" label="订单ID" width="100" />
        <el-table-column prop="roomName" label="会议室" width="180" />
        <el-table-column label="客户" width="180">
          <template #default="{ row }"> {{ row.fullName }} ({{ row.username }}) </template>
        </el-table-column>
        <el-table-column label="预订时间" width="220">
          <template #default="{ row }">
            {{ formatDateTime(row.startTime) }} - {{ formatTime(row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag
              :type="getStatusTagType(row.status)"
              :class="{
                'status-scheduled': row.status === 'SCHEDULED',
                'status-completed': row.status === 'COMPLETED',
              }"
            >
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="totalPrice" label="金额" width="120">
          <template #default="{ row }"> ¥{{ row.totalPrice?.toFixed(2) || '0.00' }} </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewDetails(row)" type="primary" plain>
              详情
            </el-button>
            <el-button
              size="small"
              @click="cancelReservation(row)"
              type="danger"
              plain
              v-if="row.status === 'PENDING_PAYMENT' || row.status === 'SCHEDULED'"
            >
              取消
            </el-button>
            <el-button
              size="small"
              @click="setInUse(row)"
              type="primary"
              plain
              v-if="row.status === 'CONFIRMED'"
            >
              设为使用中
            </el-button>
            <el-button
              size="small"
              @click="setCompleted(row)"
              type="success"
              plain
              v-if="row.status === 'IN_USE'"
            >
              设为已完成
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container mt-4">
        <div class="flex justify-between items-center w-full">
          <div class="text-sm text-gray-500">共 {{ total }} 条数据</div>
          <div>
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="total"
              layout="sizes, prev, pager, next, jumper"
              :page-sizes="[10, 20, 50, 100]"
              @size-change="fetchReservations"
              @current-change="fetchReservations"
            />
          </div>
        </div>
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="订单详情" width="50%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单ID">{{
          currentReservation.bookingId
        }}</el-descriptions-item>
        <el-descriptions-item label="会议室">{{
          currentReservation.roomName
        }}</el-descriptions-item>
        <el-descriptions-item label="客户">
          {{ currentReservation.fullName }} ({{ currentReservation.username }})
        </el-descriptions-item>
        <el-descriptions-item label="联系电话">{{
          currentReservation.phone || '无'
        }}</el-descriptions-item>
        <el-descriptions-item label="开始时间">{{
          formatDateTime(currentReservation.startTime)
        }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{
          formatDateTime(currentReservation.endTime)
        }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusTagType(currentReservation.status)">
            {{ getStatusText(currentReservation.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="金额"
          >¥{{ currentReservation.totalPrice?.toFixed(2) || '0.00' }}</el-descriptions-item
        >
        <el-descriptions-item label="备注" :span="2">{{
          currentReservation.notes || '无'
        }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { Search } from '@element-plus/icons-vue'
import { debounce } from 'lodash-es'
import { RefreshCw } from 'lucide-vue-next'

const reservations = ref([])
const loading = ref(false)
const isSearching = ref(false)
const roomNameSearch = ref('')
const customerNameSearch = ref('')
const statusFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const detailDialogVisible = ref(false)
const currentReservation = ref({})

const filteredReservations = computed(() => {
  return reservations.value.filter((reservation) => {
    const matchesRoom = reservation.roomName
      .toLowerCase()
      .includes(roomNameSearch.value.toLowerCase())
    const matchesCustomer = reservation.fullName
      .toLowerCase()
      .includes(customerNameSearch.value.toLowerCase())
    const matchesStatus = !statusFilter.value || reservation.status === statusFilter.value
    return matchesRoom && matchesCustomer && matchesStatus
  })
})

const total = computed(() => filteredReservations.value.length)

const paginatedReservations = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredReservations.value.slice(start, end)
})

const handleSearch = debounce(() => {
  isSearching.value = true
  setTimeout(() => {
    isSearching.value = false
  }, 300)
}, 500)

const resetSearch = () => {
  roomNameSearch.value = ''
  customerNameSearch.value = ''
  statusFilter.value = ''
}

const fetchReservations = async () => {
  try {
    loading.value = true
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      roomName: roomNameSearch.value,
      fullName: customerNameSearch.value,
      status: statusFilter.value,
    }
    const response = await axios.get(
      'http://localhost:8080/api/reservations/reservations-with-details',
      { params }
    )
    reservations.value = response.data.content || response.data
    total.value = response.data.totalElements || response.data.length || 0
  } catch (error) {
    console.error('Error fetching reservations:', error)
    ElMessage.error(error.response?.data?.message || '获取订单信息失败')
  } finally {
    loading.value = false
  }
}

const formatDateTime = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  })
}

const formatTime = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
  })
}

const getStatusTagType = (status) => {
  switch (status) {
    case 'PENDING_PAYMENT':
      return 'warning' // 黄色-待支付
    case 'CONFIRMED':
      return 'success' // 绿色-已确认
    case 'PAYMENT_EXPIRED':
      return 'danger' // 红色-支付超时
    case 'CANCELLATION_REQUESTED':
      return 'warning' // 黄色-取消申请中
    case 'CANCELLED':
      return 'danger' // 红色-已取消
    case 'SCHEDULED':
      return '' // 蓝色-已预约(默认)
    case 'IN_USE':
      return '' // 浅蓝色-使用中
    case 'COMPLETED':
      return '' // 灰色-已完成(自定义)
    default:
      return ''
  }
}

const getStatusText = (status) => {
  switch (status) {
    case 'PENDING_PAYMENT':
      return '待支付'
    case 'CONFIRMED':
      return '已确认'
    case 'PAYMENT_EXPIRED':
      return '支付超时'
    case 'CANCELLATION_REQUESTED':
      return '取消申请中'
    case 'CANCELLED':
      return '已取消'
    case 'SCHEDULED':
      return '已预约'
    case 'IN_USE':
      return '使用中'
    case 'COMPLETED':
      return '已完成'
    default:
      return status
  }
}

const viewDetails = (reservation) => {
  currentReservation.value = reservation
  detailDialogVisible.value = true
}

const cancelReservation = async (reservation) => {
  try {
    await ElMessageBox.confirm(`确定要取消订单 ${reservation.bookingId} 吗?`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await axios.put(`http://localhost:8080/api/reservations/${reservation.bookingId}/cancel`)
    ElMessage.success('订单已取消')
    fetchReservations()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Error cancelling reservation:', error)
      ElMessage.error(error.response?.data?.message || '取消订单失败')
    }
  }
}

const setInUse = async (reservation) => {
  try {
    await ElMessageBox.confirm(
      `确定要将订单 ${reservation.bookingId} 设为使用中吗? 会议室状态将同步更新为"使用中"`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    // 更新订单状态
    await axios.put(`http://localhost:8080/api/reservations/set-inuse/${reservation.bookingId}`)

    // 更新会议室状态为INUSE
    // if (reservation.roomId) {
    //   await axios.put(`http://localhost:8080/api/meetingrooms/${reservation.roomId}/status`, {
    //     status: 'INUSE'
    //   })
    // }

    ElMessage.success('订单和会议室状态已更新为使用中')
    fetchReservations()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Error setting reservation to in use:', error)
      ElMessage.error(error.response?.data?.message || '设置失败')
    }
  }
}

const setCompleted = async (reservation) => {
  try {
    await ElMessageBox.confirm(
      `确定要将订单 ${reservation.bookingId} 设为已完成吗? 会议室状态将同步更新为"空闲"`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    // 更新订单状态
    await axios.put(`http://localhost:8080/api/reservations/set-completed/${reservation.bookingId}`)

    // 更新会议室状态为AVAILABLE
    // if (reservation.roomId) {
    //   await axios.put(`http://localhost:8080/api/meetingrooms/${reservation.roomId}/status`, {
    //     status: 'AVAILABLE'
    //   })
    // }

    ElMessage.success('订单和会议室状态已更新为已完成')
    fetchReservations()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Error setting reservation to completed:', error)
      ElMessage.error(error.response?.data?.message || '设置失败')
    }
  }
}

onMounted(() => {
  fetchReservations()
})

defineExpose({
  fetchReservations,
})
</script>

<style scoped>
.reservation-management {
  padding: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-card__header) {
  border-bottom: 1px solid var(--el-border-color-light);
}

/* 自定义状态标签颜色 */
:deep(.el-tag.el-tag--warning) {
  background-color: #fdf6ec;
  border-color: #faecd8;
  color: #e6a23c;
}

:deep(.el-tag.el-tag--success) {
  background-color: #f0f9eb;
  border-color: #e1f3d8;
  color: #67c23a;
}

:deep(.el-tag.el-tag--danger) {
  background-color: #fef0f0;
  border-color: #fde2e2;
  color: #f56c6c;
}

:deep(.el-tag.el-tag--info) {
  background-color: #f4f4f5;
  border-color: #e9e9eb;
  color: #909399;
}

:deep(.el-tag.status-scheduled) {
  background-color: #ecf5ff;
  border-color: #d9ecff;
  color: #409eff;
}

:deep(.el-tag.status-completed) {
  background-color: #f2f6fc;
  border-color: #e8f0f9;
  color: #909399;
}

.refresh-button {
  min-width: 40px !important;
  padding: 8px !important;
  display: inline-flex !important;
  align-items: center;
  justify-content: center;
}

:deep(.refresh-button .lucide) {
  width: 16px;
  height: 16px;
}
</style>
